package com.chen.common.utils;

import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class AuthorityManagementUtil {

    // 路径匹配工具
    private static final PathMatcher pathMatcher = new AntPathMatcher();

    // 接口权限白名单配置（示例）
    private static final Map<String, List<String>> API_ROLES = new HashMap<>();

    static {
        API_ROLES.put("/admin/**", List.of("1"));
        API_ROLES.put("/user/**", List.of("0", "1"));
    }

    /**
     * 垂直权限校验
     *
     * @param claims 包含用户角色信息
     */
    public static boolean checkVerticalAuth(String requestURI, Map<String, Object> claims) {
        String userRole = null; // JWT中需存储角色字段
        try {
            userRole = claims.get("role").toString();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        // 遍历权限配置
        for (Map.Entry<String, List<String>> entry : API_ROLES.entrySet()) {
            String pathPattern = entry.getKey();
            List<String> allowedRoles = entry.getValue();

            // 匹配当前请求路径
            if (pathMatcher.match(pathPattern, requestURI)) {
                // 无需登录的接口
                if (allowedRoles.isEmpty()) return true;

                // 校验角色权限
                return allowedRoles.contains(userRole);
            }
        }

        // 默认拒绝未配置的接口
        return false;
    }
}
